package com.itcast.dao;

import com.itcast.pojo.Friendlist;
import com.itcast.pojo.Publish;
import com.itcast.utils.ConnectionFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PublishDaoImpl implements  PublishDao {

    @Override
    public List<Publish> findAll() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            //获取连接
            connection= ConnectionFactory.getConnection();
            //定义sql
            String sql="select * from publish ";
            //获取集装箱
            preparedStatement=connection.prepareStatement(sql);
            //给？赋值
            //执行sql
            resultSet=preparedStatement.executeQuery();
            List<Publish> publishes=new ArrayList<>();
            //遍历取值
            while (resultSet.next())
            {
                Publish publish=new Publish();
                publish.setUserName(resultSet.getString("user_name"));
                publish.setUserId(resultSet.getString("user_id"));
                publish.setPublishTxt(resultSet.getString("publish_txt"));
                publish.setCreateDate(resultSet.getString("create_date"));
                publish.setUserImage(resultSet.getString("user_image"));
               publishes .add(publish);
            }
            return publishes;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally{
            ConnectionFactory.close(resultSet,preparedStatement,connection);
        }
        return null;
    }

    @Override
    public void InsertPublish(Publish publish) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            //获取连接
            connection= ConnectionFactory.getConnection();
            //定义sql
            String sql="insert into publish (user_id, publish_txt, create_date, user_name,user_image)values (?,?,now(),?,?)";
            //获取集装箱
            preparedStatement=connection.prepareStatement(sql);
            //给？赋值
            preparedStatement.setString(1,publish.getUserId());
            preparedStatement.setString(2,publish.getPublishTxt());
            preparedStatement.setString(3,publish.getUserName());
            preparedStatement.setString(4,publish.getUserImage());
            //执行sql
            int result=preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionFactory.close(resultSet,preparedStatement,connection);
        }
    }
}
